//
//  DaletouViewController.m
//  DSBet
//
//  Created by 李春阳 on 2018/5/21.
//  Copyright © 2018年 Bill. All rights reserved.
//

#import "DaletouViewController.h"

#import "DaleTouModel.h"
#import "Appearance.h"
#import "MBProgressHUD+MJ.h"
#import "ThreeDBottomView.h"
#import "LotteryOrderView.h"
#import "OrderBillViewController.h"
#import "ShareValue.h"
#import "LoginViewController.h"
#import "zhoushiViewController.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface DaletouViewController ()

@property(nonatomic,strong)NSMutableArray *readArray;
@property(nonatomic,strong)NSMutableArray *bluearray;
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;

@property(nonatomic,strong)NSMutableArray *readbtnArray;
@property(nonatomic,strong)NSMutableArray *bluebtnArray;
@property(nonatomic,strong)ThreeDBottomView *bottomView;
@property (nonatomic,strong) LotteryOrderView *lotteryOrderView;

@end

@implementation DaletouViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"ffffff"];
    [self setNavConfigStartColor:@"#F57321" endColor:@"#F57321"];
    [self ApptitileView:@"大乐透"];
    [self initRedBall];
    [self initBlueBall];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"quxiaodingdanxuanhao" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeChoose) name:@"quxiaodingdanxuanhao" object:nil];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, ((Main_Screen_Width - 40)/7.0) * 5 + 70+NAV_HEIGHT, Main_Screen_Width, 0.5)];
    view.backgroundColor = [UIColor grayColor];
    [self.view addSubview:view];
    
    _bottomView = [ThreeDBottomView loadThreeDBottomView];
    [_bottomView setFrame:CGRectMake(0, Main_Screen_Height - bottom_HEIGHT - 50, Main_Screen_Width, 50)]
    ;
    [_bottomView.jixuanButton addTarget:self action:@selector(jixuanButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView.surebuttonPressed addTarget:self action:@selector(surebuttonPressed) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView.clearbutton addTarget:self action:@selector(clearbuttonPressed) forControlEvents:UIControlEventTouchUpInside];
    _bottomView.surebuttonPressed.layer.cornerRadius = 3.f;
    _bottomView.surebuttonPressed.layer.masksToBounds = YES;
    
    [self.view addSubview:_bottomView];
    
    [self reloadBall];
}

- (void)closeChoose{
    [self.readArray removeAllObjects];
    [self.bluearray removeAllObjects];
    
    [self reloadBall];
}

-(void)setModel:(DaleTouModel *)model{
    _model = model;
    self.readArray = [_model.redarray mutableCopy];
    self.bluearray = [_model.bluearray mutableCopy];
    [self reloadBall];
}

- (NSMutableArray *)readbtnArray{
    if (!_readbtnArray) {
        _readbtnArray = [NSMutableArray array];
    }
    return _readbtnArray;
}

-(NSMutableArray *)bluebtnArray{
    if (!_bluebtnArray) {
        _bluebtnArray = [NSMutableArray array];
    }
    return _bluebtnArray;
}

-(NSMutableArray *)readArray{
    if (!_readArray) {
        _readArray = [NSMutableArray array];
    }
    return _readArray;
}

-(NSMutableArray *)bluearray{
    if (!_bluearray) {
        _bluearray = [NSMutableArray array];
    }
    return _bluearray;
}

- (void)initRedBall{
    for (int i = 0; i < 35; i++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(20 + ((Main_Screen_Width - 40)/7.0) * (i % 7), ((Main_Screen_Width - 40)/7.0)*(i/7) + 60 + NAV_HEIGHT, (Main_Screen_Width - 40)/7.0 - 5, (Main_Screen_Width - 40)/7.0 - 5)];
        btn.layer.cornerRadius = ((Main_Screen_Width - 40)/7.0 - 5) / 2;
        btn.layer.masksToBounds = YES;
        btn.layer.borderColor = [UIColor grayColor].CGColor;
        btn.layer.borderWidth = 0.5;
        [btn setTitle:[NSString stringWithFormat:@"%d",i+1] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        
        btn.tag = 1000 + i +1;
        [btn addTarget:self action:@selector(redBallClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        [self.readbtnArray addObject:btn];
    }
}

- (void)initBlueBall{
    for (int i = 0; i < 12; i++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(20 + ((Main_Screen_Width - 40)/7.0) * (i % 7), ((Main_Screen_Width - 40)/7.0)*(i/7) + 85 + ((Main_Screen_Width - 40)/7.0) * 5 + NAV_HEIGHT, (Main_Screen_Width - 40)/7.0 - 5, (Main_Screen_Width - 40)/7.0 - 5)];
        btn.layer.cornerRadius = ((Main_Screen_Width - 40)/7.0 - 5) / 2;
        btn.layer.masksToBounds = YES;
        btn.layer.borderColor = [UIColor grayColor].CGColor;
        btn.layer.borderWidth = 0.5;
        btn.tag =1000+ i+1;
        [btn setTitle:[NSString stringWithFormat:@"%d",i+1] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
        [btn addTarget:self action:@selector(blueBallClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
          [self.bluebtnArray addObject:btn];
    }
}

#pragma mark - target methods
- (void)redBallClicked:(UIButton *)btn{
    btn.selected = !btn.selected;
    NSInteger inter = btn.tag - 1000;
    NSNumber *number = [NSNumber numberWithInteger:inter];
    if ([self.readArray containsObject:number]) {
        [self.readArray removeObject:number];
    }else{
        [self.readArray addObject:number];
    }
    if (btn.selected) {
        btn.backgroundColor = [UIColor redColor];
    }else{
        btn.backgroundColor = [UIColor whiteColor];
    }
    [self reloaBottomView];
}

-(void)reloaBottomView{
    
    if (self.readArray.count<5 || self.bluearray.count<2) {
        self.contentLabel.text = @"0注 共0元";
    }else{
        NSInteger count = 1;
        NSInteger bottomindexcount = 5*4*3*2*1;
        for (int i = self.readArray.count; i>0; i--) {
            count = count *i;
        }
        NSInteger currentx = self.readArray.count -5;
        NSInteger bottomcount = 1;
        if (currentx ==0) {
            bottomcount = 1;
        }else{
            for (int j= currentx; j>0; j--) {
                bottomcount = bottomcount *j;
            }
        }
        NSInteger lastcount = count/(bottomcount *bottomindexcount);
        
        NSInteger bluecount = 1;
        NSInteger bluecountbottomindexcount = 2*1;
        for (int m = self.bluearray.count; m>0; m--) {
            bluecount = bluecount *m;
        }
        NSInteger bluecurrentx = self.bluearray.count -2;
        NSInteger bluebottomcount = 1;
        if (currentx ==0) {
            bluebottomcount = 1;
        }else{
            for (int n= bluecurrentx; n>0; n--) {
                bluebottomcount = bluebottomcount *n;
            }
        }
        
        NSInteger bluelastcount = bluecount/(bluecountbottomindexcount *bluebottomcount);
        
        NSInteger allcount = bluelastcount * lastcount;
        
         self.bottomView.contentLabel.text = [NSString stringWithFormat:@"%ld注 共%ld元",allcount,allcount*2];
    }
}

-(void)reloadBall{
    
    for (int i=0; i<self.readbtnArray.count; i++) {
        UIButton *btn = self.readbtnArray[i];
        NSInteger tag = btn.tag - 1000;
        if ([self.readArray containsObject:@(tag)]) {
            btn.selected = YES;
        }else{
            btn.selected = NO;
        }
        if (btn.selected) {
            btn.backgroundColor = [UIColor redColor];
        }else{
            btn.backgroundColor = [UIColor whiteColor];
        }
    }
    
    for (int i=0; i<self.bluebtnArray.count; i++) {
        UIButton *btn = self.bluebtnArray[i];
        NSInteger tag = btn.tag - 1000;
        if ([self.bluearray containsObject:@(tag)]) {
            btn.selected = YES;
        }else{
            btn.selected = NO;
        }
        if (btn.selected) {
            btn.backgroundColor = [UIColor blueColor];
        }else{
            btn.backgroundColor = [UIColor whiteColor];
        }
    }
    [self reloaBottomView];
}

- (void)blueBallClicked:(UIButton *)btn{
    btn.selected = !btn.selected;
    NSInteger inter = btn.tag - 1000;
    NSNumber *number = [NSNumber numberWithInteger:inter];
    if ([self.bluearray containsObject:number]) {
        [self.bluearray removeObject:number];
    }else{
        [self.bluearray addObject:number];
    }
    if (btn.selected) {
        btn.backgroundColor = [UIColor blueColor];
    }else{
        btn.backgroundColor = [UIColor whiteColor];
    }
      [self reloaBottomView];
}


-(void)clearbuttonPressed{
    [self.readArray removeAllObjects];
    [self.bluearray removeAllObjects];
    
    [self reloadBall];
}

-(void)jixuanButtonPressed{
  
    NSMutableArray *readArray = [NSMutableArray array];
    NSMutableArray *blueArray = [NSMutableArray array];
    DaleTouModel *model = [DaleTouModel new];
    for (int i = 0; i < 3; i++) {
        while (readArray.count<5) {
            int x = arc4random()%35 +1;
            NSNumber *number = [NSNumber numberWithInteger:x];
            if (![readArray containsObject:number]) {
                [readArray addObject:number];
            }
            
        }
        while (blueArray.count<2) {
            int x = arc4random()%12 +1;
            NSNumber *number = [NSNumber numberWithInteger:x];
            if (![blueArray containsObject:number]) {
                [blueArray addObject:number];
            }
        }
    }
    model.redarray = [readArray mutableCopy];
    model.bluearray = [blueArray mutableCopy];
    NSMutableArray *currentarray = [NSMutableArray array];
    [currentarray addObject:model];
    self.readArray  = [readArray mutableCopy];
    self.bluearray = [blueArray mutableCopy];
    
    [self reloadBall];
}
- (void)surebuttonPressed{
    if (self.readArray.count>=5 && self.bluearray.count>=2) {
        if ([ShareValue sharedInstance].isLogin) {
            [self.view addSubview:self.lotteryOrderView];
            NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
            NSTimeInterval a = [dat timeIntervalSince1970];
            NSString *timeString = [NSString stringWithFormat:@"%.f", a];
            _lotteryOrderView.orderNumber = timeString;
            NSTimeInterval openTimeInter = [NSDate date].timeIntervalSince1970 + 60 * 10;
            NSDateFormatter *famtter = [[NSDateFormatter alloc] init];
            [famtter setDateFormat:@"yyyy-MM-dd HH:mm"];
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:openTimeInter];
            NSString *dateString = [famtter stringFromDate:[NSDate date]];
            _lotteryOrderView.openTime = dateString;
            _lotteryOrderView.jiangchijine = @"68万";
            NSInteger count = 1;
            NSInteger bottomindexcount = 5*4*3*2*1;
            for (int i = self.readArray.count; i>0; i--) {
                count = count * i;
            }
            
            NSInteger currentx = self.readArray.count -5;
            NSInteger bottomcount = 1;
            if (currentx == 0) {
                bottomcount = 1;
            }else{
                for (int j= currentx; j>0; j--) {
                    bottomcount = bottomcount *j;
                }
            }
            NSInteger lastcount = count/(bottomcount *bottomindexcount);
            
            NSInteger bluecount = 1;
            NSInteger bluecountbottomindexcount = 2*1;
            for (int m = self.bluearray.count; m>0; m--) {
                bluecount = bluecount * m;
            }
            NSInteger bluecurrentx = self.bluearray.count -2;
            NSInteger bluebottomcount = 1;
            if (currentx == 0) {
                bluebottomcount = 1;
            }else{
                for (int n = bluecurrentx; n>0; n--) {
                    bluebottomcount = bluebottomcount * n;
                }
            }
            
            NSInteger bluelastcount = bluecount / (bluecountbottomindexcount *bluebottomcount);
            
            NSInteger allcount = bluelastcount * lastcount;
            //多少注 多少钱
            NSString *str = [NSString stringWithFormat:@"%ld注 共%ld元",allcount,allcount*2];
            NSString *redstr = [self.readArray componentsJoinedByString:@" "];
            NSString *bluestr = [self.bluearray componentsJoinedByString:@" "];
            NSString *touzhuStr = [NSString stringWithFormat:@"%@ %@",redstr,bluestr];
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:touzhuStr];
            
            [attrStr addAttribute:NSForegroundColorAttributeName
                            value:[UIColor redColor]
                            range:NSMakeRange(0, redstr.length)];
            [attrStr addAttribute:NSForegroundColorAttributeName
                            value:[UIColor blueColor]
                            range:NSMakeRange(redstr.length + 1, bluestr.length)];
            _lotteryOrderView.attributedMyNumber = attrStr;
            _lotteryOrderView.zhudan = [NSString stringWithFormat:@"%ld注 共%ld元",allcount,allcount * 2];
            
            _lotteryOrderView.isTwoBtn = YES;
            
            _lotteryOrderView.twoBtnLookDetailBtnClickedBlock = ^{
                OrderBillViewController *vc = [[OrderBillViewController alloc] init];
                vc.isOrderBill = YES;
                [self.navigationController pushViewController:vc animated:YES];
            };
            
            _lotteryOrderView.contrlInfoBtnClickedBlock = ^{
                [self.readArray removeAllObjects];
                [self.bluearray removeAllObjects];
                [self reloadBall];
                zhoushiViewController *vc = [[zhoushiViewController alloc] init];
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            };

            _lotteryOrderView.twoBtnOneMoreBtnClickedBlock = ^{
                [self.readArray removeAllObjects];
                [self.bluearray removeAllObjects];
                [self reloadBall];
            };
            
            
            _lotteryOrderView.beishu = @"1倍";
            //存数据
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            //获取完整路径
            NSString *documentsDirectory = [paths objectAtIndex:0];
            
            NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"MyOrderList.plist"];//这里就是你将要存储的沙盒路径（.plist文件，名字自定义）
            NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
            if (!array) {
                array = [NSMutableArray array];
            }
            NSDictionary *dic = @{@"redStr" : redstr,@"blueStr":bluestr, @"caizhong" : @"超级大乐透",@"zhudan":[NSString stringWithFormat:@"%ld注 共%ld元",allcount,allcount*2],@"dingdanhao":timeString,@"jiangchijine":@"68万",@"kaijiangshijian":dateString, @"beishu":@"1倍",@"touzhushijian":[NSDate date]};
            [array insertObject:dic atIndex:0];
            [array writeToFile:plistPath atomically:YES];
        }else{
//            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
            [self presentViewController:self.loginNav animated:YES completion:nil];
//            [self.navigationController pushViewController:self animated:YES];
        }
    }else{
        [MBProgressHUD showError:@"至少选择5个红球，两个蓝球"];
    }
}

- (IBAction)randomSelectBtnClicked:(id)sender {
    
    NSMutableArray *readArray = [NSMutableArray array];
    NSMutableArray *blueArray = [NSMutableArray array];
    DaleTouModel *model = [DaleTouModel new];
    for (int i = 0; i < 3; i++) {
        while (readArray.count<5) {
            int x = arc4random()%35 +1;
            NSNumber *number = [NSNumber numberWithInteger:x];
            if (![readArray containsObject:number]) {
                [readArray addObject:number];
            }
            
        }
        while (blueArray.count<2) {
            int x = arc4random()%12 +1;
            NSNumber *number = [NSNumber numberWithInteger:x];
            if (![blueArray containsObject:number]) {
                [blueArray addObject:number];
            }
        }
        
        
    }
    model.redarray = [readArray mutableCopy];
    model.bluearray = [blueArray mutableCopy];
    NSMutableArray *currentarray = [NSMutableArray array];
    [currentarray addObject:model];
    self.readArray  = [readArray mutableCopy];
    self.bluearray = [blueArray mutableCopy];
    
    [self reloadBall];

    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.readArray removeAllObjects];
//    [self.bluearray removeAllObjects];
    [self reloadBall];
    [self reloaBottomView];
}

- (IBAction)sureBtnClicked:(id)sender {
    if (self.readArray.count>=5 && self.bluearray.count>=2) {
        NSInteger count = 1;
        NSInteger bottomindexcount = 5*4*3*2*1;
        for (int i = self.readArray.count; i>0; i--) {
            count = count *i;
        }
        NSInteger currentx = self.readArray.count -5;
        NSInteger bottomcount = 1;
        if (currentx ==0) {
            bottomcount = 1;
        }else{
            for (int j= currentx; j>0; j--) {
                bottomcount = bottomcount *j;
            }
        }
        NSInteger lastcount = count/(bottomcount *bottomindexcount);
        
        NSInteger bluecount = 1;
        NSInteger bluecountbottomindexcount = 2*1;
        for (int m = self.bluearray.count; m>0; m--) {
            bluecount = bluecount *m;
        }
        NSInteger bluecurrentx = self.bluearray.count -2;
        NSInteger bluebottomcount = 1;
        if (currentx ==0) {
            bluebottomcount = 1;
        }else{
            for (int n= bluecurrentx; n>0; n--) {
                bluebottomcount = bluebottomcount *n;
            }
        }
        
        NSInteger bluelastcount = bluecount/(bluecountbottomindexcount *bluebottomcount);
        
        NSInteger allcount = bluelastcount * lastcount;
        //多少注 多少钱
        NSString *str = [NSString stringWithFormat:@"%ld注 共%ld元",allcount,allcount*2];
    

    }
}

- (NSString *)getTomorrowDay:(NSDate *)aDate {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setDay:([components day]+1)];
    

    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
    [dateday setDateFormat:@"yyyy-MM-dd"];
    return [dateday stringFromDate:beginningOfWeek];
}

- (LotteryOrderView *)lotteryOrderView{
    if (_lotteryOrderView == nil) {
        _lotteryOrderView = [LotteryOrderView initView];
        _lotteryOrderView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        _lotteryOrderView.layer.cornerRadius = 5;
        _lotteryOrderView.layer.masksToBounds = YES;
    }
    return _lotteryOrderView;
}


@end
